var amapFile = require('./amap-wx.130');
//获取定位
function getLocation() {
  return new Promise((resolve, reject) => {
    tt.getLocation({
      type: 'gcj02', //返回可以用于tt.openLocation的经纬度
      success: function (res) {
        resolve(res)
      },
      fail(err) {
        reject(err)
      }
    });
  })
}
//封装用户是否授权定位
function authorizedLocation() {
  return new Promise((resolve, reject) => {
    tt.getSetting({
      success: (res) => {
        console.log(res.authSetting['scope.userLocation'])
        // res.authSetting['scope.userLocation'] === undefined  表示 初始化进入，从未授权
        // res.authSetting['scope.userLocation'] === true       表示 已授权
        // res.authSetting['scope.userLocation'] === false      表示 授权拒绝
        if (res.authSetting['scope.userLocation'] === undefined || res.authSetting['scope.userLocation'] === false) {
          tt.authorize({
            scope: "scope.userLocation",
            success: () => {
              resolve(res.authSetting)
            },
            fail: () => {
              tt.showModal({
                title: "您未开启地理位置授权",
                content: "请在系统设置中打开位置授权，以便我们为您提供更好的服务",
                success: (res) => {
                  if (res.confirm) {
                    tt.openSetting();
                    // reject(res.authSetting)
                  } else {
                    reject(res.authSetting)
                  }
                },
              });
            },
          });

        } else if (res.authSetting['scope.userLocation'] === true) {
          resolve(res.authSetting)
        } else if (res.authSetting['scope.userLocation'] === false) {
          tt.showModal({
            title: "您未开启地理位置授权",
            content: "请在系统设置中打开位置授权，以便我们为您提供更好的服务",
            success: (res) => {
              if (res.confirm) {
                tt.openSetting();
              } else {
                reject(res.authSetting)
              }
            },
          });
          // reject(res.authSetting)
        }
      }
    })
  })
}
//封装用户是否授权剪切板
function authorizedClipboard() {
  return new Promise((resolve, reject) => {
    tt.getSetting({
      success: (res) => {
        console.log('resllo', res)
        if (res.authSetting['scope.clipboard'] === undefined) {
          //   tt.authorize({
          //     scope: "scope.clipboard",
          //     success: (res) => {
          //       resolve(res)
          //     },
          //     fail: () => {
          //       tt.showModal({
          //         title: "您未开启剪切板授权",
          //         content: "请在系统设置中打开剪切板授权，以便我们为您提供更好的服务",
          //         success: (res) => {
          //           if (res.confirm) {
          //             tt.openSetting();
          //             // reject(res.authSetting)
          //           } else {
          //             reject(res.authSetting)
          //           }
          //         },
          //       });
          //     },
          //   });
          resolve(res.authSetting)
        } else if (res.authSetting['scope.clipboard'] === true) {
          resolve(res.authSetting)
        } else if (res.authSetting['scope.clipboard'] === false) {
          tt.showModal({
            title: "您未开启剪切板授权",
            content: "请在系统设置中打开剪切板授权，以便我们为您提供更好的服务",
            success: (res) => {
              if (res.confirm) {
                tt.openSetting();
                // reject(res.authSetting)
              } else {
                reject(res)
              }
            },
          });
          // reject(res.authSetting)
        }
      }
    })

  })

}

function isEmpty(obj) {
  try {
    if (obj == null || obj == undefined) {
      return true;
    }
    //判断数字是否是NaN
    if (typeof obj === "number") {
      if (isNaN(obj)) {
        return true;
      } else {
        return false;
      }
    }
    //判断参数是否是布尔、函数、日期、正则，是则返回false
    if (typeof obj === "boolean" || typeof obj === "function" || obj instanceof Date ||
      obj instanceof RegExp) {
      return false;
    }
    //判断参数是否是字符串，去空，如果长度为0则返回true
    if (typeof obj === "string") {
      if (obj.trim().length == 0) {
        return true;
      } else {
        return false;
      }
    }

    if (typeof obj === 'object') {
      //判断参数是否是数组，数组为空则返回true
      if (obj instanceof Array) {
        if (obj.length == 0) {
          return true;
        } else {
          return false;
        }
      }

      //判断参数是否是对象，判断是否是空对象，是则返回true
      if (obj instanceof Object) {
        //判断对象属性个数
        if (Object.getOwnPropertyNames(obj).length == 0) {
          return true;
        } else {
          return false;
        }
      }
    }
  } catch (e) {
    console.log(e);
    return false;
  }
}
// 判断是否登录
function validate_login() {
  if (isEmpty(tt.getStorageSync('token'))) {
    return false
  }
  return true
}
// 0：支付成功
// 1：支付超时
// 2：支付失败
// 3：支付关闭
// 4：支付取消
// 9：订单状态开发者自行获取
// 封装支付请求
function payOrderFunc(resPay) {
  return new Promise((resolve, reject) => {
    tt.pay({
      orderInfo: {
        order_id: resPay.dyOrderId,
        order_token: resPay.dyOrderToken,
      },
      service: 5,
      success: (res) => {
        if (res.code == 0) {
          resolve(res)
        } else if (res.code == 1) {
          tt.showToast({
            title: '支付超时',
            icon: 'fail'
          })
          reject(res)
        } else {
          reject(res)
        }

      },
      fail: (err) => {
        reject(err)
      }
    })
  })
}

// 抖音通用交易系统预下单 封装支付请求 
function payDyOrder(resPay) {
  return new Promise((resolve, reject) => {
    tt.requestOrder({
      data: resPay.ttRequestOrder.data, //最好也用云端返回的，也就是云端的那个data
      byteAuthorization: resPay.ttRequestOrder.byteAuthorization, //刚返回的res
      success(res) {
        console.log(res)
        // tt.setStorageSync(resPay.orderId,res.orderId);
        tt.getOrderPayment({ //获取orderId订单号后发起支付
          orderId: res.orderId,
          success(res) {
            resolve(res)
          },
          fail(err) {
            console.log('err', err)
            reject(err)
          }
        });
      },
      fail(err) {
        console.log('err', err)
        reject(err)
      }
    })
  })
}

// 去支付 抖音通用交易系统预下单 封装支付
function payDyOrderCreate(orderId) {
  return new Promise((resolve, reject) => {
    tt.getOrderPayment({ //获取orderId订单号后发起支付
      orderId: orderId,
      success(res) {
        resolve(res)
      },
      fail(err) {
        console.log('err', err)
        reject(err)
      }
    });
  })
}
// 封装富文本 图片自适应
function repairRichText(html) {
  // 去掉<img>中style /width / height属性
  let newContent = html.replace(/<img[^>]*>/gi, (match) => {
    match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '')
    match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '')
    match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '')
    match = match.replace(/style\s*=\s*(["'])(?:(?!\1).)*\1/gi, '') // 去除 style=""这样的属性
    return match
  })
  // 修改所有style里的width属性为max-width:100%
  newContent = newContent.replace(/style="[^"]+"/gi, (match) => {
    match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi,
      'max-width:100%;')
    return match
  })

  // 去掉所有<br/>标签
  newContent = newContent.replace(/<br[^>]*\/>/gi, '')
  // img标签添加style属性：max-width:100%;height:auto
  newContent = newContent.replace(/\<img/gi,
    '<img style="max-width:100%;height:auto;display:block;margin-top:0;margin-bottom:0;"'
  )
  return newContent;
}
// 公共跳转 登录后配置跳转链接
// type 跳转类型 1 navigateTo 2 redirectTo 3 reLaunch
// showTip 是否显示提示
function jumpPublicLogin(type = 1, showTip = false) {
  var curRoute = getParam()
  if (showTip) {
    tt.showToast({
      title: '请登录',
      icon: 'fail'
    })
    setTimeout(() => {
      jumpUrl(type, curRoute)
    }, 1000)
  } else {
    jumpUrl(type, curRoute)
  }
  // console.log(curRoute)
}
// 公共跳转 实名后配置跳转链接 
// type 跳转类型 1 navigateTo 2 redirectTo 3 reLaunch 
// showTip 是否显示提示
function jumpPublicRealName(type = 1, showTip = false) {
  var curRoute = getParam()
  if (showTip) {
    tt.showToast({
      title: '请实名',
      icon: 'none'
    })
    setTimeout(() => {
      jumpUrl(type, curRoute, false)
    }, 1000)
  } else {
    jumpUrl(type, curRoute, false)
  }
  // console.log(curRoute)
}
// type 跳转类型 1 navigateTo 2 redirectTo 3 reLaunch
// curRoute 跳转链接
// isLogin 是否跳转到登录页面
function jumpUrl(type, curRoute, isLogin = true) {
  var url = ''
  if (isLogin) {
    url = "/pages/login/login?linkJump=true"
    // tt.setStorageSync('linkJump', encodeURIComponent(JSON.stringify(curRoute)));
    tt.setStorageSync('linkJump', curRoute);
  } else {
    // url = "/pages/subPackages/pagesC/certification/certification?linkJump=" + encodeURIComponent(JSON.stringify(curRoute))
  }
  if (type == 1) {
    tt.navigateTo({
      url: url
    })
  } else if (type == 2) {
    tt.redirectTo({
      url: url
    })
  } else if (type == 3) {
    tt.reLaunch({
      url: url
    })
  }
}
// 获取当前url 地址
function getParam() {
  var routes = getCurrentPages(); // 获取当前打开过的页面路由数组
  var curRoute = routes[routes.length - 1].route //获取当前页面路由
  var curParam = routes[routes.length - 1].options; //获取路由参数
  // 拼接参数
  var param = ''
  // console.log(curParam)
  var i = 0
  for (var key in curParam) {
    if (i == 0) {
      param += '?' + key + '=' + curParam[key]
    } else {
      param += '&' + key + '=' + curParam[key]
    }
    i++

  }
  var pageUrl = '/' + curRoute + param
  return pageUrl
}

/**
 * 防止重复点击
 * @param {参数} fn 
 */
let pageActive = true

function preventActive(fn, time) {
  time = time || 1000;
  const self = this
  if (pageActive) {
    pageActive = false
    if (fn) fn()
    setTimeout(() => {
      pageActive = true
    }, time);
    return true
  } else {
    return false
    console.log("重复点击")
  }
}
// 解决小程序路由超过10层限制
const MAX_VALUE = 8

function navigateTo(url) {
  var pages = getCurrentPages() // 页面栈
  var len = pages.length
  if (len < MAX_VALUE) {
    tt.navigateTo({
      url
    });
  } else {
    tt.redirectTo({
      url
    });
  }
}
// 显示信息
function msg(title, duration = 1500) {
  tt.showToast({
    title,
    duration,
    icon: 'none'
  });
}
// 地图选址封装
function mapSiteSelection() {
  return new Promise((resolve, reject) => {
    tt.chooseLocation({
      success: (res) => {
        resolve(res)
      },
      fail: (err) => {
        reject(err)
        if (err.errMsg == 'chooseLocation:fail system auth deny') {
          tt.showToast({
            title: '请开启手机系统定位',
            icon: 'none'
          });
        } else if (err.errMsg == 'chooseLocation:fail auth deny') {
          tt.showModal({
            title: "您未开启地理位置授权",
            content: "请在系统设置中打开位置授权，以便我们为您提供更好的服务",
            success: (res) => {
              if (res.confirm) {
                tt.openSetting();
                // reject(res.authSetting)
              } else {}
            },
          });
        }
      },
      complete: (res) => {

      }
    });
  })
}
var myAmapFun = new amapFile.AMapWX({key: '412e6329a2c055169c1ed5b7f0e823bb'})
// 通过经纬度获取省市区
function getCurrentLocation(longitude, latitude) {
  return new Promise((resolve, reject) => {
    myAmapFun.getRegeo({
      location: `${longitude},${latitude}`,
      success(data) {
        let str = { province: '',city: '',adcode:''}
        // 拿到省份
        str.province = data[0].regeocodeData.addressComponent.province;
        // 拿到区域
        str.adcode = data[0].regeocodeData.addressComponent.adcode;
        // 拿到城市
        str.city = data[0].regeocodeData.addressComponent.city;
        if (Object.prototype.toString.call(str.city) == "[object Array]") {
          str.city = str.city.join('');
        }
        //打印得到所有地址信息
        // console.log('da拿到城市ta[0]', data[0].regeocodeData.addressComponent)
        resolve(str)
      },
      fail(err) {
        reject(err)
      }
    })
  })
}
export {
  getLocation,
  authorizedLocation,
  isEmpty,
  validate_login,
  payOrderFunc,
  repairRichText,
  jumpPublicLogin,
  jumpUrl,
  jumpPublicRealName,
  preventActive,
  closeFunc,
  openFunc,
  getParam,
  authorizedClipboard,
  navigateTo,
  payDyOrder,
  payDyOrderCreate,
  msg,
  mapSiteSelection,
  getCurrentLocation
}